package lc.com.lcpicturebackend.utils;

import java.util.Arrays;

public class MarkdownUtils {
    private static final String[] SPECIAL_CHARS = {"#", "`", "*", "_", "[", "]", "(", ")", "!", ">", "-"};

    /**
     * 判断是否为 Markdown 特殊字符
     */
    public static boolean isMarkdownSpecialChar(String chunk) {
        return Arrays.stream(SPECIAL_CHARS).anyMatch(chunk::contains);
    }


    /**
     * 修复Markdown格式
     */
    public static String repairMarkdown(String content) {
        String repairedContent = content;

        // 修复代码块
        if (countOccurrences(repairedContent, "```") % 2 != 0) {
            repairedContent += "\n```\n";
        }

        // 修复加粗标记
        if (countOccurrences(repairedContent, "**") % 2 != 0) {
            repairedContent += "**";
        }

        // 修复斜体标记
        if (countOccurrences(repairedContent, "*") % 2 != 0) {
            repairedContent += "*";
        }

        // 确保标题后有换行
        repairedContent = repairedContent.replaceAll("(#+\\s+[^\n]+)([^\\n])", "$1\n$2");

        // 确保列表项后有换行
        repairedContent = repairedContent.replaceAll("([*-]\\s+[^\n]+)([^\\n])", "$1\n$2");

        // 确保段落之间有适当的空行
        repairedContent = repairedContent.replaceAll("\n{3,}", "\n\n");

        return repairedContent;
    }

    /**
     * 判断是否为段落结束
     */
    public static boolean isParagraphEnd(String chunk) {
        return chunk.endsWith("。") || chunk.endsWith("！") ||
                chunk.endsWith("？") || chunk.endsWith(".") ||
                chunk.endsWith("!") || chunk.endsWith("?");
    }

    /**
     * 判断是否为Markdown标题行
     */
    public static boolean isHeading(String chunk) {
        return chunk.trim().matches("^#+\\s+.*");
    }

    /**
     * 判断是否为列表项
     */
    public static boolean isListItem(String chunk) {
        return chunk.trim().matches("^[*-]\\s+.*");
    }
    /**
     * 计算字符串出现次数
     */
    private static int countOccurrences(String str, String subStr) {
        return (str.length() - str.replace(subStr, "").length()) / subStr.length();
    }
}